package com.wy.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

//数据库封装类
public class DBUtil {
    static String url = "jdbc:mysql://127.0.0.1:3306/top_news?useUnicode=true&characterEncoding=utf-8&"
            +"erverTimezone=Asia/Shanghai&autoReconnect=true&useSSL=true";
    static String dbuser = "root";
    static String dbpwd = "123456";

    public Connection  conn;

    public DBUtil() {
        try{
            getConnection();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
    //定义建立数据库连接方法
    public  void   getConnection() throws Exception
    {

        //Class.forName("org.gjt.mm.mysql.Driver");
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn =  DriverManager .getConnection(url, dbuser, dbpwd);
        if(conn!=null)
            System.out.print("conn ok");
        else
            System.out.print("conn fail");
    }

    //定义执行查询方法
    public   ResultSet   query(String sql) throws Exception
    {
        //创建Statement对象
        Statement stmt = conn.createStatement();
        //执行查询
        ResultSet rs = stmt.executeQuery(sql);

        //返回结果记录集
        return rs;
    }

    //定义执行更新操作update
    public    int  update(String sql) throws Exception
    {
        //创建Statement对象
        Statement stmt = conn.createStatement();

        int result = stmt.executeUpdate(sql);    //执行更新

        return result;
    }

    public     void close()
    {
        try{
            conn.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }


}

